//
//  RechargeMoneyCell.m
//  YunGou
//
//  Created by macbook on 16/6/17.
//  Copyright © 2016年 macbook. All rights reserved.
//

#import "RechargeMoneyCell.h"
#import "NSObject+Tools.h"
@interface RechargeMoneyCell ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *moneyText;
@property (nonatomic,strong)UIButton *selectedBtn;
@end


@implementation RechargeMoneyCell

- (void)awakeFromNib {
    
    _moneyText.delegate = self;
    [_moneyText addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [_moneyText addTarget:self action:@selector(textFieldDidEndEditing:) forControlEvents:UIControlEventEditingDidEnd];
    
}

- (IBAction)moneyClicked:(id)sender {
    UIButton *btn = (UIButton *)sender;
    if (btn != _selectedBtn) {
        _selectedBtn.selected = NO;
        btn.selected = YES;
        _selectedBtn = btn;
        [_selectedBtn setAccessoryObject:btn.titleLabel.text];
    }
    if (self.block) {
        self.block(_selectedBtn);
    }
}

- (void)layoutSubviews{
    UIButton *firstBtn = [self viewWithTag:1];
    [self moneyClicked:firstBtn];
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    [button setAccessoryObject:textField.text];
    if (self.block) {
        self.block(button);
    }
}

- (void)textFieldDidChange:(UITextField *)TextField{
    for (NSInteger i = 1;i <= 5; i ++) {
        UIButton *btn = [self viewWithTag:i];
        btn.enabled = TextField.text.length == 0?YES:NO;
    }
    if (TextField.text.length == 0) {
        UIButton *firstBtn = [self viewWithTag:1];
        [self moneyClicked:firstBtn];
        [self setNeedsDisplay];
    }else{
       _selectedBtn.selected = NO;
        _selectedBtn = nil;
    }
}

//控制最多输入两位小数
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSCharacterSet *cs;
    cs = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    BOOL basicTest = [string isEqualToString:filtered];
    if (!basicTest) {
        return NO;
    }
    
    NSMutableString *futureString = [NSMutableString stringWithString:textField.text];
    [futureString insertString:string atIndex:range.location];
    NSInteger flag = 0;
    const NSInteger limited = 2;//小数点后需要限制的个数
    for (NSInteger i = futureString.length - 1; i>=0; i--) {
        if ([futureString characterAtIndex:i] == '.') {
            if (flag > limited) {
                return NO;
            }
            break;
        }
        flag++;
    }
    return YES;
}

@end
